package com.wangjiacai.utils.utils;

import com.wangjiacai.utils.enums.ResultEnum;
import com.wangjiacai.utils.web.exception.CodeMessageException;
import org.springframework.validation.BindingResult;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

public class ValidatorUtil {

    public static void valid(BindingResult bindingResult){
        if (bindingResult.hasFieldErrors()) {
            throw new CodeMessageException(ResultEnum.ParamsInvalid.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
    }

    public static void valid(ConstraintViolationException e){
        Set<ConstraintViolation<?>> set=e.getConstraintViolations();
        for(ConstraintViolation constraintViolation:set){
            throw new CodeMessageException(constraintViolation.getMessage());
        }
    }

    public static void secureValid(BindingResult bindingResult){
        if (bindingResult.hasFieldErrors()) {
            int code=Integer.parseInt(bindingResult.getFieldError().getCode());
            String message=bindingResult.getFieldError().getDefaultMessage();
            throw new CodeMessageException(code,message);
        }
    }

}
